package homework.server;

import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;

public class SafeClient implements Closeable {

    private Socket client;
    private InputStream in;
    private OutputStream out;

    private Charset defaultCharset;

    public SafeClient(Socket client) {
        this(client, Charset.defaultCharset());
    }

    private SafeClient(Socket client, Charset charset) {
        defaultCharset = charset;
        this.client = client;
        try {
            this.in = client.getInputStream();
            this.out = client.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            daemonClose();
        }
    }

    public boolean daemonClose() {
        try {
            close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public boolean isClosed() {
        return client.isClosed() && client.isInputShutdown() && client.isOutputShutdown();
    }

    @Override
    public void close() throws IOException {
        in.close();
        out.close();
        client.close();
    }
}
